class JobItemController {

    def userService
    def productService

    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        [ jobItemInstanceList: JobItem.list( params ) ]
    }

    def show = {
        def jobItemInstance = JobItem.get( params.id )

        if(!jobItemInstance) {
            flash.message = message(code:'jobitem.controller.notfound', args:[params.id])
            redirect(action:list)
        }
        else { return [ jobItemInstance : jobItemInstance ] }
    }

    def delete = {
        def jobItemInstance = JobItem.get( params.id )
        if(jobItemInstance) {
            jobItemInstance.delete()
            flash.message = "JobItem ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = message(code:'jobitem.controller.notfound', args:[params.id])
            redirect(action:list)
        }
    }

    def edit = {
        def jobItemInstance = JobItem.get( params.id )

        if(!jobItemInstance) {
            flash.message = message(code:'jobitem.controller.notfound', args:[params.id])
            redirect(action:list)
        }
        else {
            return [ jobItemInstance : jobItemInstance ]
        }
    }

    def update = {
        def jobItemInstance = JobItem.get( params.id )
        if(jobItemInstance) {
            jobItemInstance.properties = params
            if(!jobItemInstance.hasErrors() && jobItemInstance.save()) {
                flash.message = message(code:'jobitem.controller.updated', args:[jobItemInstance.id])
                redirect(action:show,id:jobItemInstance.id)
            }
            else {
                render(view:'edit',model:[jobItemInstance:jobItemInstance])
            }
        }
        else {
            flash.message = message(code:'jobitem.controller.notfound', args:[params.id])
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def jobItemInstance = new JobItem()
        jobItemInstance.properties = params
        jobItemInstance.staff = userService.currentStaff()
        return ['jobItemInstance':jobItemInstance, productRoots:productService.findRoots()]
    }

    def save = {
        def jobItemInstance = new JobItem(params)
        if(!jobItemInstance.hasErrors() && jobItemInstance.save()) {
            flash.message = message(code:'jobitem.controller.created', args:[jobItemInstance.id])
            //redirect(action:show,id:jobItemInstance.id)
            redirect(controller:'job',action:'show',id:jobItemInstance.job.id)
        }
        else {
            render(view:'create',model:[jobItemInstance:jobItemInstance])
        }
    }
}
